﻿using System;
using System.Net;
using System.Linq;
using System.ServiceModel.DomainServices.Client;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Arch.Samples.RiaServices.Infrastructure;

namespace Arch.Samples.RiaServices.Commands
{
    public class DeleteSelectedCommand<TViewModel, TEntity> : CollectionViewModelCommand<TViewModel, TEntity>
        where TViewModel : CollectionViewModelBase<TEntity>
        where TEntity : Entity
    {
        public string ConfirmMessage { get; protected set; }
        public Action<TEntity> DeletedAction { get; protected set; }
        public bool WithConfirm { get; protected set; }

        private DeleteCommand<TViewModel, TEntity> deleteCommand;

        public DeleteSelectedCommand(TViewModel viewModel, Action<TEntity> deletedAction = null, bool withConfirm = true,
            string confirmMessage = "Are you sure to delete {0} ?") : base(viewModel)
        {
            DeletedAction = deletedAction;
            ConfirmMessage = confirmMessage;
            WithConfirm = withConfirm;
            deleteCommand = new DeleteCommand<TViewModel, TEntity>(viewModel, deletedAction, false);
        }

        public override void Execute(object parameter)
        {
            if (WithConfirm)
            {
                string message = string.Format(ConfirmMessage, string.Join(", ", ViewModel.SelectedItems.Select(e => e.ToString())));
                var res = MessageBox.Show(message, message, MessageBoxButton.OKCancel);
                if (res != MessageBoxResult.OK) return;
            }

            foreach (var entity in ViewModel.SelectedItems.ToList())
            {
                deleteCommand.Execute(entity);
            }
        }
    }
}
